<template>
  <view class="dynamic-container">
    <view class="header">
      <text class="title">动态</text>
    </view>

    <!-- 分类切换标签 -->
    <view class="category-tabs">
      <view class="tab-item" :class="{ active: activeTab === 'follow' }" @tap="switchTab('follow')">关注</view>
      <view class="tab-item" :class="{ active: activeTab === 'recommend' }" @tap="switchTab('recommend')">推荐</view>
      <view class="tab-item" :class="{ active: activeTab === 'latest' }" @tap="switchTab('latest')">最新</view>
    </view>

    <!-- 动态列表 -->
    <view class="dynamic-list">
      <view class="dynamic-item" v-for="(item, index) in dynamicList" :key="item.id">
        <!-- 用户信息 -->
        <view class="item-header">
          <image :src="item.user.avatar" class="user-avatar" mode="aspectFill"></image>
          <view class="user-info">
            <text class="username">{{ item.user.name }}
              <text class="user-badge" v-if="item.user.isVip">💎</text>
              <text class="user-badge" v-if="item.user.tags && item.user.tags.length > 0">{{ item.user.tags[0] }}</text>
            </text>
            <text class="user-desc" v-if="item.user.description">{{ item.user.description }}</text>
            <text class="post-time">{{ item.time }}</text>
          </view>
          <view class="more-btn" @tap="showMoreOptions(index)">...</view>
        </view>

        <!-- 内容区域 -->
        <view class="content-section">
          <text class="content-text">{{ item.content }}</text>

          <!-- 图片画廊 -->
          <view class="image-gallery" v-if="item.images && item.images.length > 0">
            <image 
              v-for="(img, imgIndex) in item.images" 
              :key="imgIndex" 
              :src="img" 
              class="gallery-image"
              :class="{ single: item.images.length === 1 }"
              mode="aspectFill"
              @tap="previewImage(item.images, imgIndex)"
            ></image>
          </view>
        </view>

        <!-- 互动栏 -->
        <view class="interaction-bar">
          <view class="interaction-item" @tap="likePost(index)">
            <text class="interaction-icon" :class="{ liked: item.isLiked }">
              {{ item.isLiked ? '❤️' : '🤍' }}
            </text>
            <text class="interaction-text">{{ formatNumber(item.likes) }}</text>
          </view>

          <view class="interaction-item" @tap="showComments(index)">
            <text class="interaction-icon">💬</text>
            <text class="interaction-text">{{ formatNumber(item.comments) }}评论</text>
          </view>

          <view class="interaction-item" @tap="sharePost(index)">
            <text class="interaction-icon">🔄</text>
            <text class="interaction-text">分享</text>
          </view>
        </view>

        <!-- 热门评论 -->
        <view class="comments-preview" v-if="item.hotComments && item.hotComments.length > 0">
          <view class="comment-item" v-for="(comment, cIndex) in item.hotComments" :key="cIndex">
            <text class="comment-user">{{ comment.user }}：</text>
            <text class="comment-content">{{ comment.content }}</text>
          </view>
          <view class="view-all-comments" @tap="showComments(index)">查看全部评论</view>
        </view>
      </view>

      <!-- 加载更多 -->
      <view class="load-more" v-if="hasMore" @tap="loadMore">
        <text>{{ loading ? '加载中...' : '上拉加载更多' }}</text>
      </view>
      <view class="no-more" v-else-if="dynamicList.length > 0">
        <text>没有更多内容了</text>
      </view>
      <view class="empty-state" v-else-if="!loading">
        <text>暂无动态内容</text>
      </view>
    </view>

    <!-- 悬浮发布按钮 -->
    <view class="publish-btn" @tap="goToPublish">
      <text>+</text>
    </view>
  </view>
</template>

<script setup>
import { onLoad, onShow, onReachBottom } from '@dcloudio/uni-app';
import { ref } from 'vue';

// 响应式数据
const activeTab = ref('recommend'); // 当前选中的标签：关注、推荐、最新
const dynamicList = ref([]); // 动态列表数据
const loading = ref(false); // 加载状态
const hasMore = ref(true); // 是否有更多数据
const currentPage = ref(1); // 当前页码
const pageSize = ref(10); // 每页数量

// 页面加载时
onLoad(() => {
  console.log('动态页面加载');
  loadDynamicData();
});

// 页面显示时
onShow(() => {
  // 如果需要刷新数据，可以在这里调用
});

// 上拉加载更多
onReachBottom(() => {
  if (!loading.value && hasMore.value) {
    loadMore();
  }
});

// 切换分类标签
const switchTab = (tab) => {
  if (activeTab.value === tab) return;
  
  activeTab.value = tab;
  currentPage.value = 1;
  dynamicList.value = [];
  hasMore.value = true;
  loadDynamicData();
};

// 加载动态数据
const loadDynamicData = async () => {
  if (loading.value) return;
  
  loading.value = true;
  
  try {
    // 从本地存储获取token
    const storedToken = uni.getStorageSync('token');
    const tokenExpired = uni.getStorageSync('tokenExpired');
    const currentTime = Date.now();
    
    // 检查token是否存在或已过期
    let isTokenExpired = false;
    if (tokenExpired) {
      // 处理可能的时间单位不匹配问题
      if (typeof tokenExpired === 'number' && tokenExpired.toString().length < 13) {
        isTokenExpired = currentTime > (tokenExpired * 1000);
      } else {
        isTokenExpired = currentTime > tokenExpired;
      }
    }
    
    if (!storedToken || storedToken === '' || isTokenExpired) {
      // 没有token或token已过期，尝试使用默认数据
      console.log('Token不存在或已过期，使用默认数据');
      // 使用默认数据
      let newData = [];
      if (activeTab.value === 'recommend') {
        newData = getRecommendData();
      } else if (activeTab.value === 'follow') {
        newData = getFollowData();
      } else if (activeTab.value === 'latest') {
        newData = getLatestData();
      }
      
      // 更新列表数据
      if (currentPage.value === 1) {
        dynamicList.value = newData;
      } else {
        dynamicList.value = [...dynamicList.value, ...newData];
      }
      
      hasMore.value = false;
    } else {
      // 调用云函数获取动态数据
      const result = await uniCloud.callFunction({
        name: 'get-dynamic-data',
        data: {
          type: activeTab.value, // 关注、推荐、最新
          page: currentPage.value,
          pageSize: pageSize.value,
          token: storedToken
        }
      });
      
      console.log('获取动态数据结果:', result);
      
      if (result.result && result.result.code === 0 && result.result.data) {
        const newData = result.result.data.list || [];
        
        // 更新列表数据
        if (currentPage.value === 1) {
          dynamicList.value = newData;
        } else {
          dynamicList.value = [...dynamicList.value, ...newData];
        }
        
        // 检查是否有更多数据
        hasMore.value = result.result.data.hasMore || (newData.length >= pageSize.value);
      } else {
        console.error('获取动态数据失败，返回结果异常:', result);
        uni.showToast({
          title: result.result.message || '获取动态失败',
          icon: 'none'
        });
      }
    }
    
  } catch (error) {
    console.error('加载动态数据失败:', error);
    
    // 如果是网络错误，可以尝试使用默认数据
    let errorMsg = '网络错误，请稍后重试';
    if (error.errMsg && error.errMsg.includes('timeout')) {
      errorMsg = '请求超时，请检查网络连接';
    } else if (error.errMsg && error.errMsg.includes('auth')) {
      errorMsg = '登录已过期，请重新登录';
    }
    
    uni.showToast({
      title: errorMsg,
      icon: 'none'
    });
    
    // 尝试使用默认数据
    try {
      let newData = [];
      if (activeTab.value === 'recommend') {
        newData = getRecommendData();
      } else if (activeTab.value === 'follow') {
        newData = getFollowData();
      } else if (activeTab.value === 'latest') {
        newData = getLatestData();
      }
      
      // 更新列表数据
      if (currentPage.value === 1) {
        dynamicList.value = newData;
      } else {
        dynamicList.value = [...dynamicList.value, ...newData];
      }
      
      hasMore.value = false;
    } catch (defaultError) {
      console.error('加载默认数据也失败:', defaultError);
    }
  } finally {
    loading.value = false;
  }
};

// 加载更多数据
const loadMore = () => {
  if (loading.value || !hasMore.value) return;
  
  currentPage.value++;
  loadDynamicData();
};

// 点赞功能
const likePost = async (index) => {
  const postId = dynamicList.value[index].id;
  const isLiked = dynamicList.value[index].isLiked;
  
  // 先更新UI，提供即时反馈
  if (isLiked) {
    dynamicList.value[index].likes--;
    dynamicList.value[index].isLiked = false;
  } else {
    dynamicList.value[index].likes++;
    dynamicList.value[index].isLiked = true;
  }
  
  try {
    // 从本地存储获取token
    const storedToken = uni.getStorageSync('token');
    
    if (!storedToken) {
      console.log('未登录，无法点赞');
      // 如果未登录，可以弹出登录提示
      return;
    }
    
    // 调用云函数进行点赞/取消点赞
    await uniCloud.callFunction({
      name: 'like-post',
      data: {
        postId: postId,
        isLiked: !isLiked, // 新的点赞状态
        token: storedToken
      }
    });
    
    console.log('点赞操作成功');
  } catch (error) {
    console.error('点赞操作失败:', error);
    
    // 操作失败，回滚UI状态
    if (isLiked) {
      dynamicList.value[index].likes++;
      dynamicList.value[index].isLiked = true;
    } else {
      dynamicList.value[index].likes--;
      dynamicList.value[index].isLiked = false;
    }
    
    uni.showToast({
      title: '操作失败，请重试',
      icon: 'none'
    });
  }
};

// 查看评论
const showComments = (index) => {
  const postId = dynamicList.value[index].id;
  uni.navigateTo({
    url: `/pages/comments/index?postId=${postId}`
  });
};

// 分享功能
const sharePost = async (index) => {
  const postId = dynamicList.value[index].id;
  
  try {
    // 从本地存储获取token
    const storedToken = uni.getStorageSync('token');
    
    if (storedToken) {
      // 调用云函数记录分享行为
      await uniCloud.callFunction({
        name: 'record-share',
        data: {
          postId: postId,
          token: storedToken
        }
      });
    }
    
    // 显示分享菜单
    uni.showShareMenu({
      withShareTicket: true,
      menus: ['shareAppMessage', 'shareTimeline']
    });
  } catch (error) {
    console.error('记录分享行为失败:', error);
    // 即使记录失败，也继续显示分享菜单
    uni.showShareMenu({
      withShareTicket: true,
      menus: ['shareAppMessage', 'shareTimeline']
    });
  }
};

// 预览图片
const previewImage = (images, current) => {
  uni.previewImage({
    urls: images,
    current: current
  });
};

// 显示更多选项
const showMoreOptions = (index) => {
  const postId = dynamicList.value[index].id;
  uni.showActionSheet({
    itemList: ['举报', '不感兴趣', '取消'],
    success: (res) => {
      if (res.tapIndex === 0) {
        // 举报操作
        uni.showToast({
          title: '举报已提交',
          icon: 'none'
        });
      } else if (res.tapIndex === 1) {
        // 不感兴趣操作
        dynamicList.value.splice(index, 1);
      }
    }
  });
};

// 去发布页面
const goToPublish = () => {
  uni.navigateTo({
    url: '/pages/publish/index'
  });
};

// 格式化数字（大于1000显示为1k+）
const formatNumber = (num) => {
  if (num >= 1000) {
    return (num / 1000).toFixed(1) + 'k';
  }
  return num;
};

// 推荐动态数据
const getRecommendData = () => {
  return [
    {
      id: 1,
      user: {
        name: '闻小樨',
        avatar: '/static/logo.png',
        isVip: true,
        tags: ['科学家', '金华人', '现居杭州'],
        description: '90年-科学家，金华人-现居杭州'
      },
      content: '请问一下，普通人婚恋有必要签订财产协议吗？以爱之名安全感为由，又如何不打破平等原则不伤感情？',
      images: [
        '/static/logo.png',
        '/static/logo.png',
        '/static/logo.png',
        '/static/logo.png',
        '/static/logo.png',
        '/static/logo.png'
      ],
      time: '10分钟前',
      likes: 156,
      comments: 66,
      isLiked: false,
      hotComments: [
        {
          user: '王二妮',
          content: '我觉得很有必要，提前说清楚总比后来吵架好'
        },
        {
          user: '匿名用户',
          content: '关键还是看两个人的信任程度吧'
        }
      ]
    },
    {
      id: 2,
      user: {
        name: '恋爱日常',
        avatar: '/static/logo.png',
        tags: ['情感博主']
      },
      content: '分享一些恋爱小技巧，希望能帮到大家！1. 学会倾听比表达更重要 2. 适当的仪式感能增进感情 3. 给彼此留一些私人空间',
      images: [
        '/static/logo.png',
        '/static/logo.png'
      ],
      time: '30分钟前',
      likes: 235,
      comments: 42,
      isLiked: true,
      hotComments: [
        {
          user: '单身狗一枚',
          content: '学到了，希望早日脱单！'
        }
      ]
    },
    {
      id: 3,
      user: {
        name: '城市摄影师',
        avatar: '/static/logo.png',
        tags: ['摄影爱好者']
      },
      content: '周末扫街拍的一些照片，城市的角落总有不期而遇的美好 #城市摄影 #扫街',
      images: [
        '/static/logo.png',
        '/static/logo.png',
        '/static/logo.png'
      ],
      time: '1小时前',
      likes: 328,
      comments: 56,
      isLiked: false
    },
    {
      id: 4,
      user: {
        name: '美食探店',
        avatar: '/static/logo.png',
        tags: ['美食博主']
      },
      content: '发现一家超好吃的日料店，食材新鲜，环境也很赞！推荐给大家～',
      images: [
        '/static/logo.png',
        '/static/logo.png',
        '/static/logo.png',
        '/static/logo.png'
      ],
      time: '2小时前',
      likes: 189,
      comments: 34,
      isLiked: false,
      hotComments: [
        {
          user: '吃货一枚',
          content: '请问具体位置在哪里呀？看起来好好吃！'
        },
        {
          user: '美食探店',
          content: '回复 @吃货一枚: 在市中心的星光广场3楼哦'
        }
      ]
    }
  ];
};

// 关注动态数据
const getFollowData = () => {
  return [
    {
      id: 101,
      user: {
        name: '小红',
        avatar: '/static/logo.png'
      },
      content: '新买的相机到了，迫不及待想出去拍照了！📷',
      images: [
        '/static/logo.png'
      ],
      time: '10分钟前',
      likes: 42,
      comments: 12,
      isLiked: true
    },
    {
      id: 102,
      user: {
        name: '小明',
        avatar: '/static/logo.png'
      },
      content: '今天去爬山了，风景真美！大家周末都在做什么呢？',
      images: [
        '/static/logo.png',
        '/static/logo.png'
      ],
      time: '1小时前',
      likes: 25,
      comments: 8,
      isLiked: false
    }
  ];
};

// 最新动态数据
const getLatestData = () => {
  return [
    {
      id: 201,
      user: {
        name: '小李',
        avatar: '/static/logo.png'
      },
      content: '推荐一家超好吃的餐厅，菜品很精致，环境也不错！',
      images: [
        '/static/logo.png',
        '/static/logo.png',
        '/static/logo.png'
      ],
      time: '刚刚',
      likes: 12,
      comments: 3,
      isLiked: false
    },
    {
      id: 202,
      user: {
        name: '小王',
        avatar: '/static/logo.png'
      },
      content: '今天参加了一个读书会，收获满满！',
      images: [],
      time: '5分钟前',
      likes: 18,
      comments: 5,
      isLiked: true
    },
    {
      id: 203,
      user: {
        name: '小张',
        avatar: '/static/logo.png'
      },
      content: '分享一下最近的健身成果，坚持锻炼三个月，终于有了点成效！💪',
      images: [
        '/static/logo.png',
        '/static/logo.png'
      ],
      time: '15分钟前',
      likes: 78,
      comments: 21,
      isLiked: false
    }
  ];
};
</script>

<style scoped>
.dynamic-container {
  padding: 0;
  min-height: 100vh;
  background-color: #f7f7f7;
  position: relative;
}

.header {
  text-align: center;
  padding: 30rpx 0;
  background-color: white;
  border-bottom: 1rpx solid #f0f0f0;
  position: sticky;
  top: 0;
  z-index: 10;
}

.title {
  font-size: 44rpx;
  font-weight: bold;
  color: #333;
}

/* 分类标签样式 */
.category-tabs {
  display: flex;
  justify-content: center;
  background-color: white;
  padding: 20rpx 0;
  gap: 60rpx;
  position: sticky;
  top: 110rpx;
  z-index: 10;
  border-bottom: 1rpx solid #f0f0f0;
}

.tab-item {
  font-size: 32rpx;
  color: #666;
  padding: 10rpx 0;
  position: relative;
}

.tab-item.active {
  color: #6d4aff;
  font-weight: bold;
}

.tab-item.active::after {
  content: '';
  position: absolute;
  bottom: 0;
  left: 25%;
  width: 50%;
  height: 6rpx;
  background-color: #6d4aff;
  border-radius: 3rpx;
}

/* 动态列表样式 */
.dynamic-list {
  padding: 20rpx;
  display: flex;
  flex-direction: column;
  gap: 20rpx;
}

.dynamic-item {
  background-color: white;
  border-radius: 20rpx;
  padding: 30rpx;
  box-shadow: 0 4rpx 20rpx rgba(0, 0, 0, 0.05);
}

/* 用户信息样式 */
.item-header {
  display: flex;
  align-items: center;
  margin-bottom: 20rpx;
}

.user-avatar {
  width: 80rpx;
  height: 80rpx;
  border-radius: 50%;
  margin-right: 20rpx;
  border: 2rpx solid #f0f0f0;
}

.user-info {
  flex: 1;
}

.username {
  font-size: 32rpx;
  font-weight: bold;
  color: #333;
  display: block;
  margin-bottom: 5rpx;
}

.user-badge {
  font-size: 28rpx;
  margin-left: 8rpx;
}

.user-desc {
  font-size: 26rpx;
  color: #666;
  display: block;
  margin-bottom: 5rpx;
}

.post-time {
  font-size: 22rpx;
  color: #999;
}

.more-btn {
  font-size: 36rpx;
  color: #999;
  padding: 10rpx;
}

/* 内容区域样式 */
.content-section {
  margin-bottom: 20rpx;
}

.content-text {
  font-size: 30rpx;
  color: #333;
  line-height: 48rpx;
  margin-bottom: 20rpx;
  display: block;
  word-break: break-all;
}

/* 图片画廊样式 */
.image-gallery {
  display: flex;
  flex-wrap: wrap;
  gap: 10rpx;
}

.gallery-image {
  width: calc((100% - 20rpx) / 3);
  height: 260rpx;
  border-radius: 10rpx;
  background-color: #f5f5f5;
}

.gallery-image.single {
  width: 100%;
  height: 400rpx;
}

/* 互动栏样式 */
.interaction-bar {
  display: flex;
  justify-content: space-around;
  padding-top: 20rpx;
  border-top: 1rpx solid #f0f0f0;
}

.interaction-item {
  display: flex;
  align-items: center;
  gap: 10rpx;
  padding: 10rpx 20rpx;
}

.interaction-icon {
  font-size: 32rpx;
}

.interaction-icon.liked {
  animation: likeAnimation 0.3s ease;
}

@keyframes likeAnimation {
  0% {
    transform: scale(1);
  }
  50% {
    transform: scale(1.2);
  }
  100% {
    transform: scale(1);
  }
}

.interaction-text {
  font-size: 26rpx;
  color: #666;
}

.interaction-item:active {
  background-color: #f5f5f5;
  border-radius: 40rpx;
}

/* 评论预览样式 */
.comments-preview {
  margin-top: 20rpx;
  padding-top: 20rpx;
  border-top: 1rpx solid #f0f0f0;
}

.comment-item {
  margin-bottom: 15rpx;
  padding: 10rpx;
  background-color: #f9f9f9;
  border-radius: 10rpx;
}

.comment-user {
  font-size: 26rpx;
  color: #6d4aff;
  font-weight: bold;
}

.comment-content {
  font-size: 26rpx;
  color: #333;
}

.view-all-comments {
  font-size: 26rpx;
  color: #6d4aff;
  text-align: center;
  padding: 10rpx;
}

/* 加载更多样式 */
.load-more,
.no-more,
.empty-state {
  text-align: center;
  padding: 40rpx 0;
  color: #999;
  font-size: 28rpx;
}

/* 悬浮发布按钮样式 */
.publish-btn {
  position: fixed;
  right: 40rpx;
  bottom: 120rpx;
  width: 100rpx;
  height: 100rpx;
  border-radius: 50%;
  background-color: #6d4aff;
  color: white;
  display: flex;
  justify-content: center;
  align-items: center;
  font-size: 60rpx;
  box-shadow: 0 8rpx 30rpx rgba(109, 74, 255, 0.4);
  z-index: 100;
}

.publish-btn:active {
  transform: scale(0.95);
  box-shadow: 0 4rpx 20rpx rgba(109, 74, 255, 0.3);
}
</style>